import type { GlobalStoreType } from "@/typings/stores";
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

const initialState: GlobalStoreType.stateType = {
  renderer: "canvas"
};

const actions = (set: GlobalStoreType.settersStoreType) => {
  const setGlobalState = <T extends keyof GlobalStoreType.stateType>(payload: { key: T; value: GlobalStoreType.stateType[T] }) => {
    set((state: GlobalStoreType.stateType) => {
      state[payload.key] = payload.value;
    });
  };

  return { setGlobalState };
};

const devtoolsConfig = { name: "react-global-storage", enabled: true };
const persistConfig = { name: "react-global-storage" };
export const useGlobalStore = create<GlobalStoreType.storeType>()(
  devtools(
    persist(
      immer((set) => ({
        ...initialState,
        ...actions(set)
      })),
      persistConfig
    ),
    devtoolsConfig
  )
);
